package com.clkj.mobileinspector.utils;

import android.content.Context;
import android.os.Environment;

import com.lws.basic.utils.common.MyLogger;
import com.lws.basic.utils.common.TimeUtils;


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * @松 on 2019/12/13 17:21
 * 全局异常处理
 */
public class MyCrashHandler implements Thread.UncaughtExceptionHandler {

    private Thread.UncaughtExceptionHandler mDefaultHandler;
    private Context mcontext;
    private static MyCrashHandler myCrashHandler;

    private MyCrashHandler(){}

    public static synchronized MyCrashHandler newInstance() {
        if(myCrashHandler == null)
            myCrashHandler = new MyCrashHandler();
        return myCrashHandler;
    }

    /**
     * 初始化
     * @param context
     */
    public void init(Context context){
        mcontext = context;
        //系统默认处理类
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
        //设置该类为系统默认处理类
        Thread.setDefaultUncaughtExceptionHandler(this);
    }



    @Override
    public void uncaughtException(Thread t, Throwable e) {
        if(!handleExample(e) && mDefaultHandler != null) { //判断异常是否已经被处理
            mDefaultHandler.uncaughtException(t, e);
        }else {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e1) {
                MyLogger.i(e1.getMessage());
               // CrashReport.postCatchedException(e1);
            }
            //退出程序
//            android.os.Process.killProcess(android.os.Process.myPid());
//            System.exit(1);
        }
    }

    /**
     * 提示用户出现异常
     * 将异常信息保存
     * @param ex
     * @return
     */
    private boolean handleExample(Throwable ex) {
        if(ex == null)
            return false;

        //手机设备参数信息
        collectDeviceInfo(mcontext);
       // saveCrashInfoToFile(ex);
        MyLogger.i(ex.getMessage());
        return true;
    }

    /**
     * 设备信息
     * @param mcontext
     */
    private void collectDeviceInfo(Context mcontext) {


    }


    /**
     * 保存错误信息到文件中
     * @param ex
     */
    public  void saveCrashInfoToFile(Throwable ex) {

        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable exCause = ex.getCause();
        while (exCause != null) {
            exCause.printStackTrace(printWriter);
            exCause = exCause.getCause();
        }
        printWriter.close();


        //错误日志文件名称
        String fileName = "crash-" + TimeUtils.getTodayDateTime() + ".txt";
        //判断sd卡可正常使用
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //文件存储位置
            String path = Environment.getExternalStorageDirectory().getPath() + "/measureCrash/";
            File fl = new File(path);
            //创建文件夹
            if(!fl.exists()) {
                fl.mkdirs();
            }
            try {
                FileOutputStream fileOutputStream = new FileOutputStream(path + fileName);
                fileOutputStream.write(writer.toString().getBytes());
                fileOutputStream.close();

            } catch (IOException e) {
               // CrashReport.postCatchedException(e);
            }
        }
    }
}
